package com.socialrss.instagramkit;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedHashMap;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;


import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.socialrss.accounts.FollowedPerson;
import com.socialrss.accounts.InstagramNotification;
import com.socialrss.constants.SocialNetworkNames;
import com.socialrss.constants.SocialNetworkNames.SocialNetKeys;
import com.socialrss.utils.SocialRssModel;

public class NotificationCheck extends AsyncTask<Context, Void, Void> {
	@Override
	protected Void doInBackground(Context... params) {
		Context con = params[0];
		String postid = SocialRssModel.Instance(con).getLastPostId(SocialNetKeys.ins.toString());
		LinkedHashMap<String,FollowedPerson> notList = null;
		String strUrl;
		boolean firstNotificationCheck = false;
		String accesstoken = InstagramUtils.Instance().getAccessToken();
		if(accesstoken == null){
			Log.v(InstagramConstants.LOG_INFO, "Authentication fail");
			return null;
		}
		if(postid != null){
			strUrl = InstagramConstants.APIURL + "/users/self/feed?min_id=" + postid + "&access_token=" + accesstoken;
		}
		else{
			strUrl = InstagramConstants.APIURL + "/users/self/feed?count=" + 1 + "&access_token=" + accesstoken;
			firstNotificationCheck = true;
		}
		try{
			URL url = new URL(strUrl);
	
			Log.d(InstagramConstants.LOG_REQUEST, "Opening URL " + url.toString());
			HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection() ;
			urlConnection.setRequestMethod("GET");
			urlConnection.setDoInput(true);
			//urlConnection.setDoOutput(true);
			urlConnection.connect();
			String response = InstagramUtils.Instance().streamToString(urlConnection.getInputStream());
			System.out.println(response);
			JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
					
			//just get ids of each
			//number of ids will be equal to count
			JSONArray myar = jsonObj.getJSONArray("data");
			if(myar.length()>0){
				postid = myar.getJSONObject(0).getString("id");
				//if first time when checking notification
				//store post id in database and return
				if(firstNotificationCheck){			
					SocialRssModel.Instance(con).insertLastPostId(SocialNetworkNames.SocialNetKeys.ins.toString(), postid);
					return null;
				}
				notList = new LinkedHashMap<String,FollowedPerson>();
				for (int i = 0; i < myar.length(); i++) {
					JSONObject tempPost = jsonObj.getJSONArray("data").getJSONObject(i);
					String userid = tempPost.getJSONObject("user").getString("id");
					FollowedPerson myConn;
					if(notList.containsKey(userid)){
						myConn = notList.get(userid);
					}
					else{
						myConn = SocialRssModel.Instance(null).getConnectionWithUserId(userid, SocialNetKeys.ins);
					}
					
					if(myConn!=null){				
						if(myConn.isTurnedOn()){					//this means a connection who is subscribed, has post(s).		
							InstagramNotification tempNot = new InstagramNotification();
							tempNot.setLink(tempPost.getString("link"));
							tempNot.setTextContent(" has posted new photo.");
							tempNot.setImageContentLink(tempPost.getJSONObject("images").getJSONObject("thumbnail").getString("url"));
							tempNot.setDate(tempPost.getInt("created_time"));
							myConn.addNewNotification(tempNot);		//add this notification into followed person
							notList.put(myConn.getUserid(),myConn);
						}
					}
				}
				SocialRssModel.Instance(null).setLastPostId(SocialNetKeys.ins.toString(), postid);		//store id of last post
			}
			
		}
		catch(Exception e){
			e.printStackTrace();
			Log.e(InstagramConstants.LOG_ERROR, "While controlling posts from min_id : " + postid + "\n" + e.toString());
		}
		//if there is a notification, keep it in database
		if(notList != null){
			Iterator<FollowedPerson> iter = notList.values().iterator();		
			FollowedPerson tempper;
			while(iter.hasNext()){
				tempper = iter.next();
				SocialRssModel.Instance(con).insertNotification(SocialNetworkNames.SocialNetKeys.ins, tempper);
			}
		}
		return null;
	}
 }
